<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Common\Exception;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Validation\ValidationException;
use Psr\Http\Message\ResponseInterface;
use Throwable;
use Hyperf\Di\Annotation\Inject;
use App\Common\Demand\Server\Utils;
use App\Common\Exception\Store\{JwtCheckError,DataNotFound,LoginException};
class AppExceptionHandler extends ExceptionHandler
{
    /**
     * @var StdoutLoggerInterface
     */
    protected $logger;
    #[Inject]
    protected  Utils $utils;
    public function __construct(StdoutLoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        if ($throwable instanceof ValidationException) {
            return $this->exceptionResponse($response,$throwable->validator->errors()->first(),4);
        }
         //登录异常
         if ($throwable instanceof LoginException) {
            return $this->exceptionResponse($response,$throwable->getMessage(),3);
        }
        //数据未找到异常
        if ($throwable instanceof DataNotFound) {
            return $this->exceptionResponse($response,$throwable->getMessage(),2);
        }
        //tpken验证异常
        if ($throwable instanceof JwtCheckError) {
           return $this->exceptionResponse($response,$throwable->getMessage(),1);
        }
        $this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
        $this->logger->error($throwable->getTraceAsString());
        return $response->withHeader('Server', 'Hyperf')->withStatus(500)->withBody(new SwooleStream('Internal Server Error222.'));
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
    private function exceptionResponse( ResponseInterface $response,string $msg,int $code){
        // 格式化输出
        $data = json_encode($this->utils->lxErrorReturn($msg,$code), JSON_UNESCAPED_UNICODE);
        // 阻止异常冒泡
        $this->stopPropagation();
        return $response->withStatus(200)->withBody(new SwooleStream($data));
    }
}
